package admin_controller

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/models"
	"cloud-navigation/global"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

// 获取管理员日志
func GetAdminLogs(c *gin.Context) {
	var form request.AdminLogs
	page, limit, validator := request.GetPages(c)
	if validator.Message != "" {
		response.ValidateFail(c, validator.Message, validator)
		return
	}
	time1 := c.Query("time1")
	time2 := c.Query("time2")
	if err := c.ShouldBindQuery(&form); err != nil {
		field, msg := request.GetErrorMsg(form, err)
		response.ValidateFail(c, msg, response.Validator{
			Field:   field,
			Message: msg,
		})
		return
	}
	fmt.Println("form: ,", form)
	var (
		tm1   time.Time
		tm2   time.Time
		logs  []models.AdminLogs
		total int64
	)
	now := time.Now().Local().Format("2006-01-02")
	if time1 == "" && time2 == "" {
		tm1, _ = time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05")
		tm2, _ = time.Parse("2006-01-02 15:04:05", now+" 23:59:59")
	} else if time1 == "" {
		tm1, _ = time.Parse("2006-01-02 15:04:05", now+" 00:00:00")
	} else if time2 == "" {
		tm2, _ = time.Parse("2006-01-02 15:04:05", now+" 23:59:59")
	} else {
		tm1, _ = time.Parse("2006-01-02 15:04:05Z07:00", time1)
		tm2, _ = time.Parse("2006-01-02 15:04:05Z07:00", time2)
	}
	if tm1.Unix() > tm2.Unix() {
		tm1, tm2 = tm2, tm1
	}
	// fmt.Println(tm1, tm2)
	db := global.App.DB.Model(&models.AdminLogs{}).Where("created_at >= ? and created_at <= ?", tm1, tm2)
	if form.AdminID != 0 {
		db = db.Where("admin_id = ?", form.AdminID)
	}
	if form.Router != "" {
		db = db.Where("router = ?", form.Router)
	}
	db.Count(&total)
	db.Preload("Admin").Order("created_at desc").Offset(int((page - 1) * limit)).Limit(int(limit)).Find(&logs)
	response.Success(c, response.PageResponse[models.AdminLogs]{
		Total:       total,
		CurrentPage: page,
		Data:        logs,
	})
}
